<!-- eslint-disable vue/no-parsing-error -->
<template>
  <div class="work-manage">
    <!-- 作业信息部分 -->
    <div class="work-info">
       <div class="header">
         <div class="title-row">
           <h3>{{ workInfo.title }}</h3>
           <div class="score-switch">
             <el-switch v-model="scoreVisible" @change="isShowScore(scoreVisible)" />
             <span v-if="scoreVisible">对学生显示成绩</span>
             <span v-else>对学生隐藏成绩</span>
           </div>
         </div>
         <div class="tags">
           <el-tag>{{ workInfo.type === 1 ? '个人作业' : '小组作业' }}</el-tag>
           <el-tag>截止时间: {{ formatDate(workInfo.endTime) }}</el-tag>
           <el-tag>{{ workInfo.score }}分</el-tag>
         </div>
         <div class="content">{{ workInfo.content }}</div>
       </div>
     </div>

    <!-- 学生作业列表部分 -->
<div class="filter-section">
       <el-input
       v-model="searchName"
       placeholder="请输入学生姓名"
       style="width: 200px; margin-right: 20px;"
       clearable
       @input="handleSearch"
       @clear="clearSearch"
       @keyup.enter="handleSearch"
     >
       <template #suffix>
         <el-icon class="el-input__icon" @click="handleSearch">
           <Search />
         </el-icon>
       </template>
     </el-input>

    <el-radio-group v-model="filterStatus" @change="handleFilterChange">
      // eslint-disable-next-line vue/no-parsing-error
      <el-radio-button :label="null">全部({{ total }})</el-radio-button>
      <el-radio-button :label="0">未交({{ unsubmittedCount }})</el-radio-button>
      <el-radio-button :label="1">提交未批改({{ submittedCount }})</el-radio-button>
      <el-radio-button :label="2">提交已批改({{ gradedCount }})</el-radio-button>
    </el-radio-group>
  </div>

    <!-- 批量操作按钮组 -->
  <div class="batch-operations">
    <el-button plain type="primary" size="small">批量导入</el-button>
    <el-button plain type="primary" size="small">打回作业</el-button>
    <el-button plain type="primary" size="small">下载</el-button>
    <el-button plain type="primary" size="small">变更标签</el-button>
    <el-button plain type="primary" size="small">一键批改</el-button>
  </div>

  <!-- 修改表格部分 -->
  <el-table :data="studentWorks" @selection-change="handleSelectionChange">
    <el-table-column type="selection" width="55" />
    <el-table-column prop="username" label="姓名" />
    <el-table-column prop="studentNo" label="学号" />  
    <el-table-column prop="tag" label="所属标签" >
    <template #default>
      <span>默认标签</span>
    </template>
   </el-table-column>
    <el-table-column prop="submitTime" label="提交时间" :formatter="formatDate" >
    <template #default="scope">
      <span>{{ scope.row.submitTime ? formatDate(scope.row.submitTime) : '' }}</span>
    </template>
  </el-table-column>
  <el-table-column prop="score" label="成绩">
  <template #default="scope">
    <span 
      v-if="scope.row.status === 0" 
      style="color: #f56c6c; cursor: pointer;"
      @click="handleUnsubmittedClick(scope.row)"
    >
      未交
    </span>
     <span 
      v-if="scope.row.status === 1" 
      style="color: #f56c6c; cursor: pointer;"
      @click="handleUnsubmittedClick(scope.row)"
    >
      未批改
    </span>
    <span v-else>{{ scope.row.score }}</span>
  </template>
</el-table-column>
    <el-table-column label="操作" width="200">
      <template #default="scope">
        <!-- 未提交状态显示催交按钮 -->
        <el-button 
          v-if="scope.row.status === 0"
          type="primary"
          size="small"
          @click="handleExpedite(scope.row.id)"
        >
          催交
        </el-button>

        <!-- 已提交状态显示查看和评分按钮 -->
        <template v-else>
          <el-button 
            type="primary"
            size="small"
            @click="viewWork(scope.row)"
          >
            查看
          </el-button>
          <el-button 
            type="primary"
            size="small"
            @click="gradeWork(scope.row)"
          >
            评分
          </el-button>
        </template>
      </template>
    </el-table-column>
  </el-table>

   <!-- 修改分页部分 -->
   <div class="pagination-container">
     <el-pagination
       v-model:current-page="currentPage"
       v-model:page-size="pageSize"
       :total="total"
       :page-sizes="[10, 20, 50, 100]"
       layout="total, sizes, prev, pager, next"
       @size-change="handleSizeChange"
       @current-change="handleCurrentChange"
     />
   </div>

    <!-- 查看作业预览对话框 -->
    <el-dialog
      v-model="previewDialogVisible"
      title="查看作业"
      width="90%"
      :fullscreen="true"
      @closed="handleDialogClose"
    >
      <div v-if="previewWork" class="preview-container">
        <div class="preview-header">
          <span>{{ previewWork.username }} - {{ formatDate(previewWork.submitTime) }}</span>
          <div>
            <el-button type="primary" @click="downloadWork(previewWork.id)">下载文件</el-button>
          </div>
        </div>
        
        <div class="preview-content">
          <!-- PDF 预览 -->
          <iframe
            v-if="previewWork.fileType === 'application/pdf'"
            :src="previewWork.fileUrl"
            class="pdf-viewer"
            type="application/pdf"
          />
          
          <!-- 不支持的文件类型 -->
          <div v-else class="unsupported-file">
            <p>该文件类型暂不支持预览，请下载后查看</p>
          </div>
        </div>
      </div>
   </el-dialog>


    
    <!-- 打分对话框 -->
    <el-dialog
      v-model="gradeDialogVisible"
      title="学生作业"
      width="600px"
      :style="{ height: '80vh' }"  
      class="grade-dialog"         
    >
      <el-form :model="gradeForm" label-width="100px">
        <el-form-item label="学生姓名">
          <el-input v-model="gradeForm.username" disabled />
        </el-form-item>
        
        <el-form-item label="学号">
          <el-input v-model="gradeForm.studentId" disabled />
        </el-form-item>
    
        <el-form-item label="所属标签">
          <el-input 
            disabled 
            placeholder="默认标签"
          />
        </el-form-item>
    
        <el-form-item label="提交时间">
          <el-input v-model="gradeForm.submitTime" disabled />
        </el-form-item>

        <el-form-item label="作业要求">
          <el-input
            type="textarea"
            v-model="workInfo.content"
            rows="4"
            disabled
          />
        </el-form-item>
    
        <el-form-item label="下载作业">
          <el-button 
            type="primary" 
            link
            @click="downloadWork(gradeForm.studentWorkId)"
            :disabled="!gradeForm.filename"
          >
            点击下载
          </el-button>
          <span v-if="gradeForm.filename" style="margin-left: 8px; color: #909399; font-size: 13px;">
            ({{ gradeForm.filename }})
          </span>
          <span v-else style="color: #909399; font-size: 13px;">暂无文件</span>
        </el-form-item>
    
        <el-form-item label="成绩">
          <el-input v-model="gradeForm.score" />
        </el-form-item>
      </el-form>
    
      <template #footer>
        <div class="dialog-footer">
          <el-button @click="gradeDialogVisible = false">取消</el-button>
          <el-button type="primary" @click="submitGrade">确定</el-button>
        </div>
      </template>
    </el-dialog>
</div>
</template>

<script setup>
import { ref, onMounted } from 'vue'
import { ElMessage, ElMessageBox } from 'element-plus'
import { Search } from '@element-plus/icons-vue'
import { getWorkInfo, getStudentWorks, submitWorkGrade ,expediteSubmission,updateWorkStatus,getStudentWorkDetail,downloadWorkFile} from '@/api/work.js'
import Storage from '@/utils/storage'

const workId = Storage.getSession("workId");

// 响应式数据
const workInfo = ref({})
const studentWorks = ref([])
const currentPage = ref(1)
const pageSize = ref(10)
const total = ref(0)
const filterStatus = ref(null)
const selectedWorks = ref([])
const scoreVisible = ref(false)
const gradeDialogVisible = ref(false)
const previewDialogVisible = ref(false)
const previewWork = ref(null)
const searchName = ref('')
const gradedCount = ref(0)

const gradeForm = ref({
  studentWorkId: null,
  score: 0,
  message: ''
})

// 统计数据
const unsubmittedCount = ref(0)
const submittedCount = ref(0)

// 获取作业信息
const fetchWorkInfo = async () => {
  try {
    console.log('开始获取作业信息，workId:', workId, 'type:', typeof workId)
    if (!workId) {
      throw new Error('作业ID不能为空')
    }
    const res = await getWorkInfo(workId)
    console.log('作业信息接口返回：', res)
    workInfo.value = res.data
    console.log('作业信息：', workInfo.value)
  } catch (error) {
    console.error('获取作业信息失败：', error)
    ElMessage.error(error.message || '获取作业信息失败')
  }
}


// 获取学生作业列表方法
const fetchStudentWorks = async () => {
  try {
    const params = {
      workId,
      page: currentPage.value,
      pageSize: pageSize.value,
      status: filterStatus.value,
      studentName: searchName.value?.trim() || ''  // 确保参数名称与后端API一致
    }
    
    console.log('请求参数：', params) // 添加调试日志

    const res = await getStudentWorks(params)
    console.log('API响应：', res) // 添加调试日志
    
    if (res.data) {
      studentWorks.value = res.data.list
      total.value = res.data.total
      unsubmittedCount.value = res.data.unsubmittedCount
      submittedCount.value = res.data.submittedCount
      gradedCount.value = res.data.gradedCount
    }
  } catch (error) {
    console.error('获取学生作业列表失败：', error)
    ElMessage.error('获取学生作业列表失败')
  }
}


// 修改搜索处理方法
const handleSearch = async () => {
  console.log('触发搜索，关键词：', searchName.value) // 添加调试日志
  currentPage.value = 1  // 重置到第一页
  await fetchStudentWorks()
}

// 可以添加一个清空搜索的方法
const clearSearch = () => {
  searchName.value = ''
  fetchStudentWorks()
}


// 添加未交点击处理方法
const handleUnsubmittedClick = (row) => {
  ElMessageBox.confirm(
    '确定将该学生作业状态改为已交吗？',
    '提示',
    {
      confirmButtonText: '确定',
      cancelButtonText: '取消',
      type: 'warning'
    }
  ).then(async () => {
    try {

      await updateWorkStatus(row.id, 1)
            // 更新本地数据状态
            row.status = 1

      ElMessage({
        type: 'success',
        message: '状态已更新为已交'
      })
      
      // 重新获取列表数据以更新计数等信息
      fetchStudentWorks()
    } catch (error) {
      ElMessage.error('更新状态失败')
    }
  }).catch(() => {
    // 用户点击取消，不做任何操作
  })
}


// 修改查看作业方法
const viewWork = async (row) => {
  if (!row.filename) {
    ElMessage.warning('暂无提交文件')
    return
  }

  try {
    const response = await downloadWorkFile(row.id)
    
    // 根据文件名判断文件类型
    const isPDF = row.filename.toLowerCase().endsWith('.pdf')
    // 强制设置 PDF 的 content-type
    const contentType = isPDF ? 'application/pdf' : response.headers['content-type']
    
    const blob = new Blob([response.data], { type: contentType })
    const fileUrl = URL.createObjectURL(blob)
    
    previewWork.value = {
      id: row.id,
      username: row.username,
      submitTime: row.submitTime,
      filename: row.filename,
      fileUrl: fileUrl,
      fileType: contentType
    }
    
    previewDialogVisible.value = true
  } catch (error) {
    console.error('预览失败：', error)
    ElMessage.error('文件预览失败')
  }
}




// 修改评分方法
const gradeWork = async (row) => {
  try {
    // 获取学生作业详情
    const res = await getStudentWorkDetail(row.id)
    
    gradeForm.value = {
      studentWorkId: row.id,
      score: row.score || 0,
      message: row.message || '',
      username: row.studentName,
      studentId: row.studentNo,
      submitTime: row.submitTime,
      filename: row.filename || '无文件',
      content: res.data.content, // 学生提交的作业内容
    }
    
    gradeDialogVisible.value = true
  } catch (error) {
    console.error('获取作业详情失败：', error)
    ElMessage.error('获取作业详情失败')
  }
}
const isShowScore = (value) => {
  if (value) {
    ElMessage.success('已对学生显示成绩')
  } else {
    ElMessage.warning('已对学生隐藏成绩')
  }
}

const submitGrade = async () => {
  try {
    await submitWorkGrade(gradeForm.value)
    ElMessage.success('评分成功')
    gradeDialogVisible.value = false
    fetchStudentWorks()
  } catch (error) {
    ElMessage.error('评分失败')
  }
}
//下载作业
const downloadWork = async (studentWorkId) => {
  try {
    const response = await downloadWorkFile(studentWorkId)
    
    // response 现在是完整的 axios 响应对象
    const blob = new Blob([response.data], { 
      type: response.headers['content-type'] || 'application/octet-stream' 
    })
    
    // 从响应头获取文件名
    const contentDisposition = response.headers['content-disposition']
    let filename = 'download'
    if (contentDisposition) {
      const filenameMatch = contentDisposition.match(/filename[^;=\n]*=((['"]).*?\2|[^;\n]*)/)
      if (filenameMatch && filenameMatch[1]) {
        filename = filenameMatch[1].replace(/['"]/g, '')
      }
    }
    
    const downloadUrl = window.URL.createObjectURL(blob)
    const link = document.createElement('a')
    link.href = downloadUrl
    link.download = decodeURIComponent(filename)
    document.body.appendChild(link)
    link.click()
    document.body.removeChild(link)
    window.URL.revokeObjectURL(downloadUrl)
    
    ElMessage.success('文件下载成功')
  } catch (error) {
    console.error('下载失败：', error)
    ElMessage.error('文件下载失败')
  }
}


// 批量操作相关方法
const handleSelectionChange = (selection) => {
  selectedWorks.value = selection
}

const handleFilterChange = (value) => {
  filterStatus.value = value
  fetchStudentWorks()
}


// 添加催交处理方法
const handleExpedite = async (id) => {
  try {
    await expediteSubmission(id)
    ElMessage.success('已发送催交提醒')
    fetchStudentWorks()
  } catch (error) {
    ElMessage.error('催交失败')
  }
}

// 分页相关方法
const handleSizeChange = (val) => {
  pageSize.value = val
  fetchStudentWorks()
}

const handleCurrentChange = (val) => {
  currentPage.value = val
  fetchStudentWorks()
}

// 工具方法
const formatDate = (date) => {
  if (!date) return '-'
  return new Date(date).toLocaleString()
}

// 修改状态文本方法
// eslint-disable-next-line no-unused-vars
const getStatusText = (status) => {
  const statusMap = {
    0: '未提交',
    1: '已提交未批改',
    2: '已批改'
  }
  return statusMap[status]
}

// 修改状态样式方法

// 生命周期钩子
onMounted(() => {
  fetchWorkInfo()
  fetchStudentWorks()
})
</script>

<style scoped>
.work-manage {
  padding: 20px;
}

.work-info {
  margin-bottom: 20px;
  padding: 20px;
  border: 1px solid #eee;
  border-radius: 4px;
}


.title-row {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 15px;
}

.score-switch {
  display: flex;
  align-items: center;
  gap: 10px;
  color: #606266;
  font-size: 14px;
}

.score-switch .el-switch {
  margin-right: 8px;
}

.filter-section {
  margin-bottom: 20px;
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.operations {
  display: flex;
  gap: 10px;
}

.tags {
  margin: 10px 0;
  display: flex;
  gap: 10px;
}

.content {
  margin-top: 10px;
  color: #666;
}

.top_r {
  display: block;
  flex-direction: row;
  font-family: PingFangSC, PingFangSC-Medium;
  font-weight: 500;
  text-align: left;
  color: #4285f4;
  line-height: 8px;
}

.work-preview-info {
  margin-bottom: 20px;
  padding: 10px;
  background-color: #f5f7fa;
  border-radius: 4px;
}

.work-preview-content {
  min-height: 200px;
}

.preview-file {
  margin: 10px 0;
}

.preview-image {
  max-width: 100%;
  max-height: 500px;
  object-fit: contain;
}

.file-info {
  padding: 10px;
  border: 1px solid #eee;
  border-radius: 4px;
  display: flex;
  align-items: center;
  gap: 10px;
}

.no-content {
  text-align: center;
  color: #909399;
  padding: 40px 0;
}

.preview-container {
  height: calc(100vh - 120px);
  display: flex;
  flex-direction: column;
}

.preview-header {
  padding: 10px;
  display: flex;
  justify-content: space-between;
  align-items: center;
  border-bottom: 1px solid #eee;
  background-color: #fff;
  position: sticky;
  top: 0;
  z-index: 1;
}

.preview-content {
  flex: 1;
  overflow: auto;
  padding: 20px;
  background-color: #f5f5f5;
}

.pdf-viewer {
  width: 100%;
  height: 100%;
  border: none;
  background-color: #fff;
  box-shadow: 0 2px 12px 0 rgba(0, 0, 0, 0.1);
}

.image-viewer {
  max-width: 100%;
  margin: 0 auto;
  display: block;
  box-shadow: 0 2px 12px 0 rgba(0, 0, 0, 0.1);
}

.unsupported-file {
  text-align: center;
  padding: 40px;
  background-color: #fff;
  border-radius: 4px;
  box-shadow: 0 2px 12px 0 rgba(0, 0, 0, 0.1);
}

.pdf-container {
  position: relative;
  width: 100%;
  height: 100%;
  display: flex;
  justify-content: center;
  background-color: #fff;
}

.pdf-loading,
.pdf-error {
  position: absolute;
  top: 50%;
  left: 50%;
  transform: translate(-50%, -50%);
  text-align: center;
  color: #909399;
  display: flex;
  flex-direction: column;
  align-items: center;
  gap: 10px;
}

.pdf-loading .el-icon,
.pdf-error .el-icon {
  font-size: 24px;
  margin-bottom: 10px;
}

.preview-content {
  flex: 1;
  overflow: auto;
  padding: 20px;
  background-color: #f5f5f5;
  display: flex;
  justify-content: center;
}

.pdf-viewer {
  width: 100%;
  max-width: 1000px; /* 限制最大宽度 */
  height: 100%;
  background-color: #fff;
  box-shadow: 0 2px 12px 0 rgba(0, 0, 0, 0.1);
}


.search-row {
  display: flex;
  align-items: center;
  gap: 20px;
}

.batch-operations {
  display: flex;
  gap: 10px;
  justify-content: flex-end; /* 靠右对齐 */
}

/* 自定义按钮样式 */
.batch-operations .el-button {
  background-color: white;
  border-color: #d4d4d4;
  color: #6c9ff1;
}

.batch-operations .el-button:hover {
  background-color: #f0f7ff;
}

.pagination-container {
  margin-top: 20px;
  display: flex;
  justify-content: center;
  padding: 15px 0;
}

/* 添加一点底部间距 */
.pagination-container .el-pagination {
  margin-bottom: 20px;
}
.preview-container {
  height: calc(100vh - 120px);
  display: flex;
  flex-direction: column;
}

.preview-content {
  flex: 1;
  overflow: auto;
  padding: 20px;
  background-color: #f5f5f5;
  display: flex;
  justify-content: center;
}

.pdf-viewer {
  width: 100%;
  height: 100%;
  border: none;
  background-color: #fff;
  box-shadow: 0 2px 12px 0 rgba(0, 0, 0, 0.1);
}

.grade-dialog {
  :deep(.el-dialog) {
    height: 70vh;
    display: flex;
    flex-direction:column;
    margin-top: 15vh !important;
  }

  :deep(.el-dialog__body) {
    flex: 1;
    overflow-y: auto;
    padding: 20px;
  }

  :deep(.el-dialog__footer) {
    padding: 10px 20px;
    border-top: 1px solid #dcdfe6;
  }
}

.dialog-content {
  height: 100%;
}

.dialog-footer {
  text-align: right;
}
</style>
